//
//  FileSerialization.m
//  WeSchoolStudent
//
//  Created by safiri on 15/9/23.
//  Copyright © 2015年 safiri. All rights reserved.
//

#import "ZSFileSerialization.h"

@implementation ZSFileSerialization

//MARK: - 获得磁盘上最常用文件夹的路径
//from UIApplication+YYAdd
+ (NSURL *)documentsURL {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
+ (NSString *)documentsPath {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}

+ (NSURL *)cachesURL {
    return [[[NSFileManager defaultManager]
             URLsForDirectory:NSCachesDirectory
             inDomains:NSUserDomainMask] lastObject];
}
+ (NSString *)cachesPath {
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
}

+ (NSURL *)libraryURL {
    return [[[NSFileManager defaultManager]
             URLsForDirectory:NSLibraryDirectory
             inDomains:NSUserDomainMask] lastObject];
}
+ (NSString *)libraryPath {
    return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
}

+ (NSString *)fileCreatePathInDocumentsWithFileName:(NSString *)fileName {
    return [[self documentsPath] stringByAppendingPathComponent:fileName];
}
+ (NSString *)fileCreatePathInCachesWithFileName:(NSString *)fileName {
    return [[self cachesPath] stringByAppendingPathComponent:fileName];
}
+ (NSString *)fileCreatePathInLibraryWithFileName:(NSString *)fileName {
    return [[self libraryPath] stringByAppendingPathComponent:fileName];
}

+ (BOOL)fileRemoveOfURL:(NSURL *)fileURL {
    BOOL flag = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:fileURL.path]) {
        if (![fileManager removeItemAtURL:fileURL error:nil]) {
            flag = NO;
        }
    }
    return flag;
}
+ (BOOL)fileRemoveOfPath:(NSString *)filePath {
    BOOL flag = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        if (![fileManager removeItemAtPath:filePath error:nil]) {
            flag = NO;
        }
    }
    return flag;
}

//创建文件路径
+ (BOOL)fileCreatDirectoryWithPath:(NSString *)directoryPath {
    BOOL result = YES;
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:directoryPath];
    if (!isExist) {
        NSError *error;
        //withIntermediateDirectories YES,则在创建最深层文件前,将会创建所有的父文件夹.
        //attributes:一个传递给系统可以影响文件夹将如何创建的属性字典
        BOOL isSuccess = [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (!isSuccess) {
            result = NO;
            NSLog(@"creat Directory Failed. errorInfo:%@",error);
        }
    }
    return result;
}

//创建文件
+ (BOOL)fileCreatWithPath:(NSString *)filePath {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:filePath];
    if (isExist) {
        return YES;
    }
 
    //stringByDeletingLastPathComponent:删除最后一个路径节点
    NSString *directoryPath = [filePath stringByDeletingLastPathComponent];
    isSuccess = [self fileCreatDirectoryWithPath:directoryPath];;
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    return isSuccess;
}

//移动文件
+ (BOOL)fileMoveFromPath:(NSString *)fromFilePath toPath:(NSString *)toFilePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromFilePath]) {
        NSLog(@"Error: fromFilePath Not Exist");
        return NO;
    }
    if (![fileManager fileExistsAtPath:toFilePath]) {
        NSLog(@"Error: toFilePath Not Exist");
        return NO;
    }
    NSString *headerComponent = [toFilePath stringByDeletingLastPathComponent];
    if ([self fileCreatWithPath:headerComponent]) {
        return [fileManager moveItemAtPath:fromFilePath toPath:toFilePath error:nil];
    } else {
        return NO;
    }
}

//拷贝文件
+ (BOOL)fileCopyFromPath:(NSString *)fromFilePath toPath:(NSString *)toFilePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fromFilePath]) {
        NSLog(@"Error: fromFilePath Not Exist");
        return NO;
    }
    if (![fileManager fileExistsAtPath:toFilePath]) {
        NSLog(@"Error: toFilePath Not Exist");
        return NO;
    }
    NSString *headerComponent = [toFilePath stringByDeletingLastPathComponent];
    if ([self fileCreatWithPath:headerComponent]) {
        return [fileManager copyItemAtPath:fromFilePath toPath:toFilePath error:nil];
    } else {
        return NO;
    }
}
//获取文件夹下文件列表
+ (NSArray *)fileGetFileListInDirectoryPath:(NSString *)directoryPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:directoryPath error:&error];
    if (error) {
        NSLog(@"fileGetFileListInDirectoryPath, errorInfo:%@",error);
    }
    return fileList;
}
//获取文件大小
+ (long long)fileGetSizeWithPath:(NSString *)filePath {
    unsigned long long fileLength = 0;
    NSNumber *fileSize;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:nil];
    if ((fileSize = [fileAttributes objectForKey:NSFileSize])) {
        fileLength = [fileSize unsignedLongLongValue];
    }
    return fileLength;
}
//获取文件创建时间
+ (NSString *)fileGetCreatDateWithPath:(NSString *)filePath {
    NSString *date = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:nil];
    date = [fileAttributes objectForKey:NSFileCreationDate];
    return date;
}

//获取文件所有者
+ (NSString *)fileGetOwnerWithPath:(NSString *)filePath {
    NSString *fileOwner = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:nil];
    fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName];
    return fileOwner;
}
//获取文件更改日期
+ (NSString *)fileGetChangeDateWithPath:(NSString *)filePath {
    NSString *date = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:nil];
    date = [fileAttributes objectForKey:NSFileModificationDate];
    return date;
}

//保存文件
+ (BOOL)fileSaveData:(NSData *)data withPath:(NSString *)filePath {
    BOOL result = YES;
    result = [self fileCreatWithPath:filePath];
    if (result) {
        result = [data writeToFile:filePath atomically:YES];
        if (!result) {
            NSLog(@"%s Failed",__FUNCTION__);
        }
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
    }
    return result;
}

//追加写文件
+ (BOOL)fileAppendData:(NSData *)data withPath:(NSString *)filePath {
    BOOL result = [self fileCreatWithPath:filePath];
    if (result) {
        NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
        [handle seekToEndOfFile];
        [handle writeData:data];
        [handle synchronizeFile];
        [handle closeFile];
        return YES;
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
        return NO;
    }
}

//获取文件数据
+ (NSData *)fileGetData:(NSString *)filePath {
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    NSData *fileData = [handle readDataToEndOfFile];
    [handle closeFile];
    return fileData;
}

//读取文件
+ (NSData *)fileGetData:(NSString *)filePath startIndex:(long long)startIndex length:(NSInteger)length {
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    [handle seekToFileOffset:startIndex];
    NSData *data = [handle readDataOfLength:length];
    [handle closeFile];
    return data;
}

@end
